/**

 @Name：qbdms 公共业务
 @Author：wzt
 @Site：http://www.layui.com/admin/
 @License：LPPL

 */

layui.define(['table','upload','publicMethods','qbdmsForm'],function(exports){
    var $ = layui.$
        ,layer = layui.layer
        ,laytpl = layui.laytpl
        ,setter = layui.setter
        ,admin = layui.admin
        ,table = layui.table
        ,upload = layui.upload
        ,publicMethods=layui.publicMethods
        ,form = layui.qbdmsForm;

    //公共业务的逻辑处理可以写在此处，切换任何页面都会执行

    //退出
    admin.events.logout = function(){
        //执行退出接口
        window.location.href =serverPath.qbdmsPath + "/logout"
    };

    var common = {
        //监听排序事件  lay-filter   even  正常的json ,paramFormLayFilter  查询form的layui-Filter,需要多个方法   ，隔开
        tableSort: function(tableLayFilter,even,paramFormLayFilter){
            table.on('sort('+tableLayFilter+')', function(obj){
                var where = {};
                var Filter=$("form.layui-form").attr("lay-filter");
                if(paramFormLayFilter){
                    Filter=paramFormLayFilter
                }
                $("form[lay-filter='"+Filter+"']").find(".filter-value").each(function() {
                    where[this.name] = this.value;
                });

                table.reload(tableLayFilter, {
                    initSort: obj //记录初始排序，如果不设的话，将无法标记表头的排序状态。
                    ,where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
                        sortName:!!($(this).data('sortname'))?$(this).data('sortname'):obj.field //排序字段
                        ,sortOrder: obj.type //排序方式
                    } ,page: {
                        curr: 1 //重新从第 1 页开始
                    }

                });
                if(even){
                    for(var key in even){
                        if (even[key]) {
                            even[key]();
                        }
                    }
                }
                // totalFilter.initQuery(tableLayFilter,true);
                setTimeout(function () {
                    form.val(Filter,where);
                    table.resize(tableLayFilter);
                },2000)
            });
        },

        //table表格回车搜索功能
        //搜索按钮和查询框被  class为ccpui-enterSel的div包裹
        //selDom为输入框dom元素 clickDOm为点击搜索按钮dom元素
        tableSelectCon:function(selDom,clickDOm,parentSle){
            $(selDom).focus(function () {
                $(this).unbind()
                $(this).keydown(function(event){
                    if(event.keyCode ==13){
                        $(this).parents(parentSle).find(clickDOm).click()
                    }
                });
            })
            if($(".layui-table-box .layui-table-body").find(".layui-none").text()=="无数据"){
                // $(".layui-table-cell").css("width","auto")
                var tableWidth = $(".layui-table-header table").width()
                $(".layui-table-box .layui-table-body").find(".layui-none").css("width",tableWidth)
            }
        },

        /**
         * 监听table带条件渲染事件
         * @param tableLayFilter      表的layui-Filter
         * @param paramFormLayFilter  查询form的layui-Filter
         * @param paramJson           tableReload额外的参数json{"name":"value"}
         * @param isClear             是否清空form中参数  true 清空  false 不清空
         * @param isPage              是否分页,有分页不需要传值,没有分页需要传值true
         * @param limit               每页显示的记录数，如果不传值，默认10条每页
         */
        tableConditionRender: function(tableLayFilter,paramFormLayFilter,paramJson,isClear,isPage,limit){
            var params = {};
            try {
                if(paramJson){
                    if (typeof paramJson == 'string') {
                        params=JSON.parse(paramJson);
                    }else if(typeof paramJson == "object"){
                        if(paramJson){
                            params = paramJson;
                        }
                    }
                }
            } catch(e) {
                throw "Parameter format error -->"+e;
            }
            if(!limit){
                limit=20;
            }
            if(!isPage){
                var page={curr: 1, limit: limit};
                params.page=page;
            }

            if(paramFormLayFilter){
                if(isClear){
                    $("form[lay-filter='"+paramFormLayFilter+"']").find(".filter-value").each(function() {
                        params.where[this.name] = "";
                    });
                }else{
                    $("form[lay-filter='"+paramFormLayFilter+"']").find(".filter-value").each(function() {
                        params.where[this.name] = this.value;
                    });
                }
            }
            params.height = publicMethods.tabHeight()
            table.reload(tableLayFilter, params);
            if(paramFormLayFilter){
                if(!isClear){
                    setTimeout(function () {
                        form.val(paramFormLayFilter,params.where);
                    },0)
                }
            }
            setTimeout(function(){
                table.resize(tableLayFilter);
            },10);
            $('.selchBtn button i.screen').addClass("data-iconcommon_uparrow").removeClass('data-iconcommon_downarrow')
        },

        // 数据表单初始化
        updateForm:function (props) {
            if(props.name){
                var id;
                if(props.idValue == '' || props.idValue == null){
                    id = publicMethods.getQueryByName('id');
                }else{
                    id = props.idValue;
                }
                form.render();
                // 表单内时间初始化
                var timeList =  publicMethods.formInfoTimeInit(props.name);
                if(!!id){
                    if(props.primary != null && props.primary != ""){
                        $(props.primary).val(id);
                    }else{
                        $(".id").val(id);
                    }
                    publicMethods.formEcho({
                        name:props.name,
                        path:$('[lay-filter*='+props.name+']').attr('requrl'),
                        method: "GET",
                        data: {
                            id:id
                        },
                        ajaxCallback:function (data) {
                            //表单初始赋值
                            var returnDate = data.data;
                            // 存在时间处理
                            if(timeList.length>0){
                                var dateList = $(".time-init");
                                for(var i=0;i<dateList.length;i++){
                                    var da = dateList[i];
                                    var classList = da.classList;
                                    if(classList&&classList.contains("times")){//HH:mm:ss
                                        returnDate[timeList[i]] = publicMethods.timeData(returnDate[timeList[i]],'2');
                                    }else if(classList&&classList.contains("datetimes")){//yyyy-MM-dd HH:mm:ss
                                        returnDate[timeList[i]] = publicMethods.timeData(returnDate[timeList[i]],'1');
                                    }else if(classList&&classList.contains("year")){
                                        returnDate[timeList[i]] = publicMethods.timeData(returnDate[timeList[i]],'3');}
                                    else if(classList&&classList.contains("month")){
                                            returnDate[timeList[i]] = publicMethods.timeData(returnDate[timeList[i]],'4');
                                        // console.log(returnDate[timeList[i]])
                                    }else{//yyyy-MM-dd
                                        returnDate[timeList[i]] = publicMethods.timeData(returnDate[timeList[i]]);
                                    }
                                }
                            }
                            typeof props.dataCallback == "function" ? props.dataCallback(data) : null;
                            typeof props.getCallback == "function" ? props.getCallback(data) : null;
                        }
                    });

                }
                //监听提交
                var submitName = $('[lay-filter*='+props.name+'] [lay-submit]');
                publicMethods.update({
                    name:'submit('+submitName.attr('lay-filter')+')',
                    path:submitName.attr('requrl'),
                    updateCallback:props.updateCallback?props.updateCallback:null,
                    beforeSubmitFun:props.beforeSubmitFun?props.beforeSubmitFun:null
                });
                form.verify(publicMethods.formVerify);

            }
        },

        /*扩展方法开始 ----------------------------------------*/

        //通用上报
        report:function (tableName,dataId,modelKey,tableLayFilter,paramFormLayFilter,repeatReporting,className,procDefId) {
            var load ;
            if(dataId.length == 0){
                layer.alert(publicMethods.confirmStyle('请先选择一行数据进行操作!'),{title: false,skin: 'confirm-class'});
            }else{
                layer.confirm(publicMethods.confirmStyle('确定上报当前数据吗？'),{title: false,skin: 'confirm-class'}, function () {
                    load = layer.load(1, {
                        shade: [0.3, '#ccc'] //0.1透明度的白色背景
                    });
                    $.ajax({
                        url:serverPath.qbdmsPath +"/qbdms/commonality/report",
                        type:"POST",
                        data:{tableName:tableName,dataId:dataId,modelKey:modelKey,repeatReporting:repeatReporting,className:className,procDefId:procDefId},
                        dataType:"json",
                        success:function (data) {
                            layer.alert(publicMethods.confirmStyle(data.msg),{title: false,skin: 'confirm-class'});
                            table.resize(tableLayFilter);
                            layer.close(load);//关闭layer.load
                            window.Initialization();
                        },error:function (XMLHttpRequest, textStatus, errorThrown) {
                            layer.alert(publicMethods.confirmStyle("数据上报失败！" + XMLHttpRequest.status),{title: false,skin: 'confirm-class'});
                            totalFilter.init(tableLayFilter,true);
                            layer.close(load);//关闭layer.load
                        }
                    })
                });
            }
        },
        //无需上报
        doNotNeedReport:function (tableName,dataId,tableLayFilter,paramFormLayFilter,className) {
            var load;
            if(dataId.length == 0){
                layer.confirm(publicMethods.confirmStyle("请先选择一行数据进行操作!"),{title: false,skin: 'confirm-class'});
            }else{
                layer.confirm('确定当前数据无需上报吗？', function () {
                    load = layer.load(1, {
                        shade: [0.3, '#ccc'] //0.1透明度的白色背景
                    });
                    $.ajax({
                        url:serverPath.qbdmsPath +"/qbdms/commonality/doNotNeedReport",
                        type:"POST",
                        data:{tableName:tableName,dataId:dataId,className:className},
                        dataType:"json",
                        success:function (data) {
                            layer.alert(data.msg);
                            table.resize(tableLayFilter);
                            layer.close(load);//关闭layer.load
                            window.Initialization();
                        },error:function (XMLHttpRequest, textStatus, errorThrown) {
                            layer.close(load);//关闭layer.load
                            layer.alert("数据无需上报失败！" + XMLHttpRequest.status);
                        }
                    })
                });
            }
        },
        //退回待修改
        returnAndUpdate:function (tableName,dataId,tableLayFilter,paramFormLayFilter,returnMsg,className) {
            var load;
            if(dataId.length == 0){
                layer.confirm(publicMethods.confirmStyle("请先选择一行数据进行操作!"),{title: false,skin: 'confirm-class'});
            }else{
                layer.confirm('确定当前数据需要退回待修改吗？', function () {
                    load = layer.load(1, {
                        shade: [0.3, '#ccc'] //0.1透明度的白色背景
                    });
                    $.ajax({
                        url:serverPath.qbdmsPath +"/qbdms/commonality/returnAndUpdate",
                        type:"POST",
                        data:{tableName:tableName,dataId:dataId,returnMsg:returnMsg,className:className},
                        dataType:"json",
                        success:function (data) {
                            layer.alert(data.msg);
                            table.resize(tableLayFilter);
                            layer.close(load);//关闭layer.load
                            window.Initialization();
                        },error:function (XMLHttpRequest, textStatus, errorThrown) {
                            layer.close(load);//关闭layer.load
                            layer.alert("数据退回失败！" + XMLHttpRequest.status);
                        }
                    })
                });
            }
        },

        /**
         * 初始化数据字典
         * @param objName
         * @param dataList
         * @param defaultVal 默认值
         * @param callbackFun 其他表数据
         */
        initDicData:function(objName, dataList, defaultVal, callbackFun){
            if (document.getElementsByName(objName).length == 0) {return;}
            for (var i = 0; i < document.getElementsByName(objName).length; i++) {
                var optionObj = document.createElement("option");
                document.getElementsByName(objName)[i].appendChild(optionObj);
                for (var j = 0; j < dataList.length; j++) {
                    var item = dataList[j];
                    var optionObj = document.createElement("option");
                    optionObj.text = item.itemName;
                    optionObj.value = item.itemValue;
                    typeof callbackFun == "function" ? callbackFun(optionObj, item) : null;
                    document.getElementsByName(objName)[i].appendChild(optionObj);
                }
            }

            //看是否有默认值，有就赋值，没有就退出
            if(!defaultVal){form.render(); return;}

            setSeleceDefaultVal(objName, defaultVal);

            form.render();
        },

        /**
         * 设置下拉框的默认值
         * @param objName
         * @param defaultVal
         */
        setSeleceDefaultVal:function(objName, defaultVal){
            if(!defaultVal && !objName){return;}

            var ops = document.getElementsByName(objName).item(0).options;
            for (var i = 0; i < ops.length; i++) {
                var tempValue = ops[i].value;
                if (tempValue == defaultVal) {
                    ops[i].selected = true;
                }
            }
        },


        parsePrivacyLevel: function (privacyLevel) {
            if (privacyLevel == "1") {
                return "公开";
            } else if (privacyLevel == "2") {
                return "内部";
            } else if (privacyLevel == "3") {
                return "秘密";
            } else if (privacyLevel == "4") {
                return "机密";
            }
        },

        parseDicVal: function (itemVal, dicList) {
            var returnVal = "";
            for (var i = 0, len = dicList.length; i < len; i++) {
                if (dicList[i].itemValue == itemVal) {
                    returnVal = dicList[i].itemName;
                    break;
                }
            }
            return returnVal;
        },
        filterRecord:function (data) {
            return publicMethods._filterRecord(data);
        },
        //-- 初始化 数据字典 结束 --------------------------------------------------------------
        //顶部筛选按钮的伸缩方法 tableName:页面表格的Id,isReload:是否初始化（true、false）
        //options{number:一行的表单数量，width：窗口临界宽度}
        initScreenTop:function (tableName, isReload,isNOTable,options) {
            if (isReload){
                if(parseInt($('.selch .layui-row').css('width'))>=(options?options.width?options.width:1099:1099)){
                    if ($('.selch .layui-row>div').length>(options?options.number?options.number:4:4)){
                        $('.selch .selchBtn .screenParent').show();
                        $('.selch .layui-row>div').each(function (v,i) {
                            if (v>(options?options.number?options.number-1:3:3)){
                                $(i).hide();
                            }else {
                                $(i).show();
                            }
                        })
                    }else {
                        $('.selch .selchBtn .screenParent').hide();
                    }
                }else {
                    if ($('.selch .layui-row>div').length>2){
                        $('.selch .selchBtn .screenParent').show();
                        $('.selch .layui-row>div').each(function (v,i) {
                            if (v>1){
                                $(i).hide();
                            }else {
                                $(i).show();
                            }
                        })
                    }else {
                        $('.selch .selchBtn .screenParent').hide();
                    }
                }
                if (!isNOTable){
                    setTimeout(function(){
                        table.resize(tableName);
                    },0);
                }
                window.onresize = function(){
                    if(parseInt($('.selch .layui-row').css('width'))>=(options?options.width?options.width:1099:1099)){
                        if ($('.selch .layui-row>div').length>(options?options.number?options.number:4:4)){
                            $('.selch .selchBtn .screenParent').show();
                            $('.selch .layui-row>div').each(function (v,i) {
                                if (v>(options?options.number?options.number-1:3:3)){
                                    $(i).hide();
                                }else {
                                    $(i).show();
                                }
                            })
                        }else {
                            $('.selch .selchBtn .screenParent').hide();
                            $('.selch .layui-row>div').each(function (v,i) {
                                if (v>(options?options.number?options.number-1:3:3)){
                                    $(i).hide();
                                }else {
                                    $(i).show();
                                }
                            })
                        }
                    }else {
                        if ($('.selch .layui-row>div').length>2){
                            $('.selch .selchBtn .screenParent').show();
                            $('.selch .layui-row>div').each(function (v,i) {
                                if (v>1){
                                    $(i).hide();
                                }else {
                                    $(i).show();
                                }
                            })
                        }else {
                            $('.selch .selchBtn .screenParent').hide();
                        }
                    }
                    $('.selchBtn button i.screen').addClass("data-iconcommon_downarrow").removeClass('data-iconcommon_uparrow')
                    setTimeout(function(){
                        table.resize(tableName);
                    },100);
                }
            }else {
                $('.selchBtn button i.screen').toggleClass("data-iconcommon_downarrow").toggleClass('data-iconcommon_uparrow')
                if(parseInt($('.selch .layui-row').css('width'))>=(options?options.width?options.width:1099:1099)){
                    $('.selch .layui-row>div').each(function (v,i) {
                        if (v>(options?options.number?options.number-1:3:3)){
                            $(i).toggle();
                        }
                    })
                }else {
                    $('.selch .layui-row>div').each(function (v,i) {
                        if (v>1){
                            $(i).toggle();
                        }
                    })
                }
                if (!isNOTable){
                    setTimeout(function(){
                        table.resize(tableName);
                    },0);
                }
            }
        },
        verifyTitleAdd:function (item) {
            var tx = ""
            if ($(item).hasClass("fileUpload")){
                if ($(item).parent().parent().hasClass("qbdms-temTable-td")){
                    tx = $(item).parent().parent().parent().siblings("tr.qbdms-temTable-thead").children("td").eq($(item).parent().parent().index()).text();
                }else {
                    tx =  $(item).parent().parent().parent().siblings("label").text();
                }
            }else {
                if ($(item).parent().hasClass("qbdms-temTable-td")){
                    tx = $(item).parent().parent().siblings("tr.qbdms-temTable-thead").children("td").eq($(item).parent().index()).text();
                }else {
                    tx =  $(item).parent().siblings("label").text();
                }
            }
            tx = tx.replace("*"," ")
            return tx?tx:""
        },
        //附件上传  isSub:是否子表（true、false） upLoadSize（上传文件大小限制） isMultiFile(是否多文件) upLoadNumber(设置同时可上传的文件数量，0为不限制) callBack(上传成功的回调函数)
        // uploadfun :function (selectName,acceptMime,exts,secSelect,isSub,upLoadSize,isMultiFile,upLoadNumber,callBack) {
        uploadfun :function (selectName,options,callBack) {
            var load;
            var uploadInst = upload.render({
                elem: selectName //绑定元素
                , url: serverPath.qbdmsPath + setter.sysLinkPath + 'attachFile/fileUpload' //上传接口
                , accept: 'file'
                , size: options.upLoadSize?options.upLoadSize:204800 //设置文件最大可允许上传的大小，单位 KB。不支持ie8/9。为 0 则不限制。
                , acceptMime: options.acceptMime//控制默认显示类型
                , exts: options.exts
                , auto: true
                ,multiple:options.isMultiFile?options.isMultiFile:false
                , number: options.upLoadNumber||options.upLoadNumber==0?options.upLoadNumber:1
                , before: function () {
                    //上传遮罩层
                    load = layer.load(1);
                }
                , done: function (res) {
                    if(options.isSub){
                        layer.close(load);
                        var fileSecLevel = '<div style="float: left" class="fileSecLevel layui-input-inline">' + options.secSelect + "</div>";
                        if (res.code === 0 && res.data && res.data.fileList.length > 0) {
                            var fileOne = res.data.fileList[0],
                                oneFile = '<span class="file-id" fileId=' + fileOne.fileId + '>'+fileSecLevel +'<i style="float:right;" class="iconfont data-iconcommon_close deleteFile"></i><span class="file-name" title="点击下载文件" onclick="downFile(this)" style="margin: 0 20px 0 55px;display: block;line-height:24px; "><i class="iconfont data-iconcommon_fujian" style="margin-right: 5px"></i>' + fileOne.fileName + '.' + fileOne.extName + '</span>' +
                                    '</span>';
                            this.item.siblings(".uploadFileList").html(oneFile);
                            $(selectName).hide()
                            //-  附件 开始 ------------------------------------------------------
                            this.item.siblings(".uploadFileList").each(function (i,v) {
                                common.constructFileStr(v)
                            });
                            //- 附件 开始 ------------------------------------------------------
                            form.render("select");
                        }
                    }else {
                        layer.close(load);
                        if(options.isMultiFile){
                            var fileSecLevel = '<div class="fileSecLevel layui-input-inline">' + options.secSelect + "</div>";
                            if (res.code === 0 && res.data && res.data.fileList.length > 0) {
                                var fileOne = res.data.fileList[0],
                                    oneFile = '<span class="file-id" style="margin-right: 20px;" fileId=' + fileOne.fileId + '>' + fileSecLevel + '<span class="file-name" title="点击下载文件" onclick="downFile(this)"><i class="iconfont data-iconcommon_fujian" style="margin-right: 5px"></i>' + fileOne.fileName + '.' + fileOne.extName + '</span>' +
                                        '<i class="iconfont data-iconcommon_close deleteFile"></i></span>';
                                this.item.siblings(".uploadFileList").append(oneFile);

                                //-  附件 开始 ------------------------------------------------------
                                this.item.siblings(".uploadFileList").each(function (i, v) {
                                    common.constructFileStr(v)
                                });
                                //- 附件 开始 ------------------------------------------------------
                                form.render("select");
                            }
                        }else {
                            var fileSecLevel = '<div class="fileSecLevel layui-input-inline">' + options.secSelect + "</div>";
                            if (res.code === 0 && res.data && res.data.fileList.length > 0) {
                                var fileOne = res.data.fileList[0],
                                    oneFile = '<span class="file-id" style="margin-right: 20px;" fileId=' + fileOne.fileId + '>' + fileSecLevel + '<span class="file-name" title="点击下载文件" onclick="downFile(this)"><i class="iconfont data-iconcommon_fujian" style="margin-right: 5px"></i>' + fileOne.fileName + '.' + fileOne.extName + '</span>' +
                                        '<i class="iconfont data-iconcommon_close deleteFile"></i></span>';
                                this.item.siblings(".uploadFileList").html(oneFile);

                                //-  附件 开始 ------------------------------------------------------
                                this.item.siblings(".uploadFileList").each(function (i, v) {
                                    common.constructFileStr(v)
                                });
                                //- 附件 开始 ------------------------------------------------------
                                form.render("select");
                            }
                        }
                    }
                    callBack?callBack(res,this):null
                }
                ,allDone: function(obj){ //当文件全部被提交后，才触发
                    console.log(obj.total); //得到总文件数
                    console.log(obj.successful); //请求成功的文件数
                    console.log(obj.aborted); //请求失败的文件数
                }
                , error: function () {
                }
            });
        },
        stateType:function (d) {
            if(d.reportStatusStr=='待报集团'||d.reportStatusStr=='待上报'||d.reportStatusStr=='待确认'||d.reportStatusStr=='报院审批中'||d.reportStatusStr=='报院中'||d.reportStatusStr=='报集团审批中'||d.reportStatusStr=='报集团中'||d.reportStatusStr=='待审批'||d.reportStatusStr=='审批中'||d.reportStatusStr=='院内审批中'||d.reportStatusStr=='院退回中'||d.reportStatusStr=='集团退回中'||d.reportStatusStr=='院内待审批'||d.reportStatusStr=='院内审批中'||d.reportStatusStr=='待下发'||d.reportStatusStr=='下发中'||d.reportStatusStr=='退回待修改中'||d.reportStatusStr=='院无需上报中'||d.reportStatusStr=='集团无需上报中'){
                return '<i style="display: inline-block;margin-right:5px;width:6px;height:6px;background:rgba(38,130,255,1);border-radius:50%;"></i>'+ d.reportStatusStr
            }else if(d.reportStatusStr=='报院审批未通过'||d.reportStatusStr=='报院失败'||d.reportStatusStr=='审批未通过'||d.reportStatusStr=='报集团审批未通过'||d.reportStatusStr=='报集团失败'||d.reportStatusStr=='集团退回'||d.reportStatusStr=='院退回失败'||d.reportStatusStr=='集团退回失败'||d.reportStatusStr=='院内审批未通过'||d.reportStatusStr=='集团无需上报失败'||d.reportStatusStr=='院无需上报失败'||d.reportStatusStr=='下发失败'||d.reportStatusStr=='退回待修改失败'){
                return '<i style="display: inline-block;margin-right:5px;width:6px;height:6px;background:#F04134;border-radius:50%;"></i>'+ d.reportStatusStr
            }else if(d.reportStatusStr=='报院成功'||d.reportStatusStr=='报集团成功'||d.reportStatusStr=='已确认'||d.reportStatusStr=='集团新增'||d.reportStatusStr=='已下发'||d.reportStatusStr=='已审减'){
                return '<i style="display: inline-block;margin-right:5px;width:6px;height:6px;background:#67C23A;border-radius:50%;"></i>'+ d.reportStatusStr
            }else if(d.reportStatusStr=='无需上报'){
                return '<i style="display: inline-block;margin-right:5px;width:6px;height:6px;background:#A0A0A0;border-radius:50%;"></i>'+ d.reportStatusStr
            }else if(d.reportStatusStr=='退回待修改'){
                return "<a style=\"cursor: pointer;color:red\" onclick=\"layer.open({title: '退回意见',content: '" + d.returnmsg + "'});\"><i style=\"display: inline-block;margin-right:5px;width:6px;height:6px;background:rgba(38,130,255,1);border-radius:50%;\"></i>" + d.reportStatusStr + "</a>";
            }
        },
        redNum:function (d) {
                return '<span style="color: #F07878">'+d+'</span>'
        },
        issueStateType:function(d){
            if(d.status=='待下发'||d.status=='下发中'){
                return '<i style="display: inline-block;margin-right:5px;width:6px;height:6px;background:rgba(38,130,255,1);border-radius:50%;"></i>'+ d.status
            }else if(d.status=='下发失败'){
                return '<i style="display: inline-block;margin-right:5px;width:6px;height:6px;background:#F04134;border-radius:50%;"></i>'+ d.status
            }else if(d.status=='已下发'||d.status=='已审减'){
                return '<i style="display: inline-block;margin-right:5px;width:6px;height:6px;background:#67C23A;border-radius:50%;"></i>'+ d.status
            }
        },
        //    列表页初始化数据
        parseDataList:function (res,data) {
            $.each(res.data, function (i, v) {
                $.each(data, function (index, vals) {
                    var a = vals
                    if (v[vals] === '') {
                        v[vals] = "-"
                    }
                })
            })
        },
        //-- 设置控件是否必填 开始 --------------------------------------------------------------
        /**
         * 设置控件是否必填，按照isRequired值设置是必填还是不必填
         * 统一构造lay-verify所必须的字符串，然后设置该属性
         * @param componentName
         * @param isRequired
         */
        setComponentRequired:function (componentNameArr, isRequired, validCondition,checkdepts) {
            if (!validCondition) {
                validCondition = "required";
            }
            for (var i = 0, len = componentNameArr.length; i < len; i++) {
                var componentName = componentNameArr[i];

                if ($("[name='" + componentName + "']").length == 0) {
                    return;
                }
                if ('fCheckapprovalnumber' === componentName || 'fIfconclusion' === componentName) {
                    // 验收批复文号、是否结题 不是必填项
                    continue;
                }
                // lay-verify="required"
                var verifyStr = $("[name='" + componentName + "']").attr("lay-verify");
                if (verifyStr == null) {
                    verifyStr = "";
                }
                var block = $("[name='" + componentName + "']").closest(".layui-input-block.qbdms-input");
                if (isRequired) {
                    block && block.prev("label") && block.prev("label").find("span:hidden") && block.prev("label").find("span").attr("hidden",false);
                    verifyStr = verifyStr.replace("|" + validCondition, "");
                    verifyStr = verifyStr.replace(validCondition, "");
                    verifyStr += "|" + validCondition;
                } else {
                    block && block.prev("label") && block.prev("label").find("span:hidden") && block.prev("label").find("span").attr("hidden",true);
                    verifyStr = verifyStr.replace("|" + validCondition, "");
                    verifyStr = verifyStr.replace(validCondition, "");
                }
                $("[name='" + componentName + "']").attr("lay-verify", verifyStr);
            }

            var checkdepts = eval(checkdepts);
            // var checkdepts = JSON.parse(checkdepts);
            var checkdeptsHtml = "<option></option>";
            $.each(checkdepts, function (index, obj) {
                checkdeptsHtml += "  <option code='" + obj.code + "' value='" + obj.orgName + "'  >" + obj.orgName + "</option>";
            });
            $("select[name='fCheckdept']").html(checkdeptsHtml);
            // form.render();
            // $("input[name='fCheckdept']").val('${zcdw}');
        },
        //-- 清空表单控件值 开始 --------------------------------------------------------------
        clearComponentVal:function (componentNameArr) {
            for (var i = 0, len = componentNameArr.length; i < len; i++) {
                var componentName = componentNameArr[i];
                var objArr = document.getElementsByName(componentName);

                if (objArr.length == 0) {
                    return;
                }
                for (var j = 0; j < objArr.length; j++) {
                    document.getElementsByName(componentName).item(j).value = "";
                }
            }
            // form.render("select");
        },
        //构建file的字符串
        constructFileStr:function (v) {
            var filesJsonStr = "";
            $(v).find(".file-id").each(function () {
                var fileId = $(this).attr("fileid");
                var fileName = $(this).find("span").text();
                var fileLevel = $(this).find("option:selected").val();
                var fileLevelText = $(this).find("option:selected").text();
                filesJsonStr += '{"fileId":"' + fileId + '","fileName":"' + fileName + '","fileLevel":"' + fileLevel + '", "fileLevelText":"' + fileLevelText + '"},';
            });
            filesJsonStr = filesJsonStr.substring(0, filesJsonStr.length - 1);
            if (filesJsonStr != "") {
                filesJsonStr = '[' + filesJsonStr + ']';
            }
            var fileUploadName = $(v).attr("fileUploadName");
            $(v).prev().val(filesJsonStr);
            // $("input[name='"+fileUploadName+"']").val(filesJsonStr);
        },

        /**
         * list页面导入文件功能
         * @param tableId           lay-filter
         * @param impActionUrl      导入动作要用的url
         * @param isExport          是否需要下载模板
         * @param exportTempUrl     如果下载模板，模板的url
         */
        importInit:function (tableId,impActionUrl,isExport,exportTempUrl) {
            var html='<form class="layui-form" action="" style="padding: 10px 75px;">' +
                '    <div class="layui-upload-drag" type="file" name="xmlFile" id="xmlFile" style="color: #C0C4CC">' +
                '        <i class="layui-icon"></i>' +
                '        <p>点击上传，或将文件拖拽到此处</p></div>' +
                '    <div class="layui-btn-container layui-footer" style="position: absolute;bottom: 10px">';
                if(isExport){
                   html=html+ '<button type="button" class="layui-btn layui-btn-sm" id="exportButton">下载模板</button>'
                }
               html=html+ '<button type="button" class="layui-btn layui-btn-sm" id="importButtonClick">导入</button>'+
                   '<button type="button" class="layui-btn layui-btn-sm" id="importButton" style="display: none"></button>'+
                '<button class="layui-btn layui-btn-sm" type="button" id="return">取消</button></div></form>';
                var index=layer.open({
                    type: 1,
                    title: "导入",
                    shade: 0.3,
                    skin:'importInit',
                    area: ['400px', '300px'],
                    content:html
                });
            //关闭弹窗
            $('#return').click(function () {
                layer.close(index);
            });
            $('#exportButton').click(function () {
                window.location.href = serverPath.qbdmsPath + exportTempUrl;
            });
            var loadIndex;
            $('#importButtonClick').click(function () {
                if($('.importInit .layui-upload-choose').length>0){
                    $("#importButton").trigger('click');
                }else{
                    layer.alert(publicMethods.confirmStyle("请先选择文件!"),{title: false,skin: 'confirm-class'});
                    return false
                }
            });
            upload.render({
                elem: '#xmlFile'
                , url: serverPath.qbdmsPath + impActionUrl
                , accept: 'file'
                , acceptMime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel'
                , multiple: false
                , exts: 'xlsx|xls'
                , auto: false //选择文件后不自动上传
                , bindAction: '#importButton' //指向一个按钮触发上传
                , before : function(){
                    loadIndex = layer.load(2,{shade: [0.1,'#000']});
                }
                , done: function (res, index2,upload) {
                    if (res.code == 1) {
                        layer.alert(publicMethods.confirmStyle(res.msg),{title: false,skin: 'confirm-class'});
                        layer.close(loadIndex);
                    } else {
                        layer.alert(publicMethods.confirmStyle(res.msg),{title: false,skin: 'confirm-class'}, function (index1) {
                            layui.table.reload(tableId);
                            layer.close(index1);
                            layer.close(index);
                            layer.close(loadIndex)
                        });
                    }
                },
                error:function(){
                    layer.close(loadIndex)
                }
            });
        },

        /**
         * 附件密级保存功能
         * @param files     附件ID及密级数据数组
         */
        setFileLevel:function (files) {
            var saveResult=true;
            if(files && files.length>0){
                $.ajax({
                    type:"post",
                    url: serverPath.qbdmsPath +"/extend/attachFile/update",
                    async:false,
                    contentType : "application/json",
                    dataType: 'json',
                    data: JSON.stringify(files),
                    success:function(ret){
                        if(ret.code==1){
                            //保存密级失败
                            saveResult= false;
                            layer.alert(publicMethods.confirmStyle("附件密级保存失败！"),{title: false,skin: 'confirm-class'});
                        }
                    }
                });
            }
            return saveResult;
        }
    };

    //对外暴露的接口
    exports('common', common);
});